package com.example.netty.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class EchoServer {

    public static void main(String[] args) {
        new EchoServer().bind(801);
    }

    public void bind(int port) {
        /**
         * 第一个经常被叫做‘boss’，用来接收进来的连接。第二个经常被叫做‘worker’，用来处理已经被接收的连接，一旦‘boss’接收到连接，
         * 就会把连接信息注册到‘worker’上。如何知道多少个线程已经被使用
         */
        EventLoopGroup bossgroup = new NioEventLoopGroup(1);
        EventLoopGroup workgroup = new NioEventLoopGroup(1);
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossgroup, workgroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                // .childOption(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 换行符处理粘包、拆包
                        pipeline.addLast("framer",
                                new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                        // 编码
                        pipeline.addLast("decoder", new StringDecoder());
                        // 解码
                        pipeline.addLast("encoder", new StringEncoder());
                        // 业务逻辑
                        pipeline.addLast("handler", new SimpleChatServerHandler());
                    }
                });

        try {
            // 绑定成功，同步等待成功
            ChannelFuture f = b.bind(port).sync();
            // 同步等待服务器端口关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossgroup.shutdownGracefully();
            workgroup.shutdownGracefully();
        }

    }
}
